#-*- coding: utf-8 -*-

import datetime

_cached_data = {}

class DataUnit(object):
	
	def __init__(self, data, minutes=30):
		self.data = data
		self.expires = datetime.datetime.now() + \
			datetime.timedelta(minutes=minutes)
	
	@property
	def expired(self):
		return self.expires < datetime.datetime.now()

def get_cached_data(key):
	if _cached_data.has_key(key):
		unit = _cached_data[key]
		if unit.expired:
			_cached_data.pop(key)
			return None
		else:
			return unit.data
	return None

def save_to_cache(key, data, minutes=30):
	_cached_data[key] = DataUnit(data, minutes=minutes)

def clear_caches():
	_cached_data.clear()

def cached(key='', minutes=30):
	'''this is a decorator.'''
	def handler_gen(view_func):
		def handler(*args, **kargs):
			cachingkey = '%s.%s' % (key, view_func.func_name)
			cached_results = get_cached_data(cachingkey)
			if cached_results:
				return cached_results
			results = view_func(*args, **kargs)
			save_to_cache(cachingkey, results, minutes=minutes)
			return results
		return handler
	return handler_gen



